<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>私有方法和私有属性</title>
</head>
<body>
    <h1>私有方法和私有属性</h1>

    <script>
        // 使用#声明私有属性和方法
        class IncapsulatedClass {
            #privateField = 42;
            #privateMethod() {
                return 'private method';
            }

            publicMethod() {
                console.log(this.#privateField);
                console.log(this.#privateMethod());
            }
        }

        const instance = new IncapsulatedClass();
        instance.publicMethod(); // 42, "private method"
        // console.log(instance.#privateField); // 语法错误
        // instance.#privateMethod(); // 语法错误

        // 私有字段可以设置getter和setter
        class Counter {
            #count = 0;

            get value() {
                return this.#count;
            }

            set value(v) {
                if (v < 0) throw new Error('计数器不能为负数');
                this.#count = v;
            }

            increment() {
                this.#count++;
            }
        }

        // 实际应用：带验证的用户类
        class User {
            #password;
            
            constructor(username, password) {
                this.username = username;
                this.#password = this.#hashPassword(password);
            }

            #hashPassword(password) {
                // 模拟密码哈希
                return `hashed_${password}`;
            }

            #validatePassword(password) {
                return this.#password === this.#hashPassword(password);
            }

            login(password) {
                if (this.#validatePassword(password)) {
                    console.log('登录成功');
                    return true;
                }
                console.log('密码错误');
                return false;
            }
        }

        const user = new User('张三', '123456');
        user.login('123456'); // 登录成功
        user.login('wrong'); // 密码错��
    </script>
</body>
</html> 